package com.it.mongo.test;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.it.mongo.model.dto.BookDTO;
import com.it.mongo.service.BookMongoService;
import com.it.mongo.model.json.JsonString;
import com.it.mongo.service.BookMongoService02;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import java.util.Optional;


@SpringBootTest
@RunWith(SpringRunner.class)
public class BookMongoControllerTest02 {

    @Autowired
    private BookMongoService02 bookMongoService;

    /**
     * 新增)(单个新增)
     */
    @Test
    public void insert() {
        BookDTO bookDTO = new BookDTO();
        bookDTO.setId("7");
        bookDTO.setName("万界圣主");
        bookDTO.setPrice("17.8");
        bookDTO.setType("仙侠");
        bookDTO.setReadedNum(Double.parseDouble("10.7"));
        bookMongoService.insert(bookDTO);
    }

//    /**
//     * 新增（批量新增）
//     */
    @Test
    public void insertBatch(){
        // 拿到示例json数据
        String jsonString = JsonString.jsonString;
        // json转对象集合
        List<BookDTO> bookDTOList = JSON.parseArray(jsonString, BookDTO.class);
        bookMongoService.insert(bookDTOList);
    }

    /**
     * 修改
     */
    @Test
    public void update() {
        BookDTO bookDTO = new BookDTO();
        bookDTO.setId("5");
        bookDTO.setName("万界圣主");
        bookDTO.setPrice("17.9");
        bookDTO.setType("仙侠");
        bookDTO.setReadedNum(Double.parseDouble("10.7"));
        bookMongoService.save(bookDTO);

    }

    /**
     * 查询所有
     */
    @Test
    public void findAll() {
        List<BookDTO> allBookInfo = bookMongoService.findAll();
        System.out.println(allBookInfo);
    }

    /**
     * 根据id查询:精准
     */
    @Test
    public void findByName() {
        String id = "5";
        Optional<BookDTO> byId = bookMongoService.findById(id);
        System.out.println(byId);
    }


    /**
     * 根据阅读量：排序
     */
    @Test
    public void findReRange() {
        List<BookDTO> allBookInfo = bookMongoService.findAll(Sort.by(Sort.Direction.ASC,"readedNum"));
        System.out.println(allBookInfo);
    }

}